import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex); //vue的插件机制

//Vuex.Store 构造器选项
const store = new Vuex.Store({
	state: { //存放状态
		token: !!uni.getStorageSync('token') ? uni.getStorageSync('token') : '',
		user: !!uni.getStorageSync('user') ? JSON.parse(uni.getStorageSync('user')) : {},
		shopList: !!uni.getStorageSync('shopList') ? uni.getStorageSync('shopList') : [],
		cartNum: 0
	},
	getters: {
		isLogin(state) {
			return !!state.token;
		},
		// cartNum(state){
		// 	return 0;
		// }
	},
	mutations: {
		Mlogin(state, payload) {
			state.token = payload.token;
			state.user = payload.user;
			uni.setStorageSync("user", JSON.stringify(payload.user));
			uni.setStorageSync("token", payload.token);
		},
		Mlogout(state) {
			state.user = {};
			state.token = '';
			uni.removeStorageSync('user');
			uni.removeStorageSync('token');
		},

		//购物车
		setCartNum(state, data) {
			state.cartNum = data
		},
		setShopList(state, data) {
			state.shopList = data.shopList
			state.cartNum = data.shopList.length
			uni.setStorageSync('shopList', data.shopList);
		},
		cartCountChange(state, payload) {

			const list = res.cart_list.slice()
			commit('setShopList', list)
		},
		delShop(state, payload) {
			// commit('setShopList', cart_list)
		},
		addToCart(state, product) {
			const productInCart = state.shopList.find(item => item.id === product.id);
			if (productInCart) {
				productInCart.num++;
			} else {
				state.shopList.push(product);
			}
			uni.setStorageSync('shopList', state.shopList);
		}

	},
	actions: {
		loginAction(context, payload) {
			context.commit('Mlogin', payload);
		},
		logout(context) {
			context.commit('Mlogout');
		}
	}

})


// import Vue from 'vue';
// import Vuex from 'vuex';
// Vue.use(Vuex);
// export default new Vuex.Store({
// 	state: {
// 		cart: []
// 	},
// 	mutations: {
// 		addToCart(state, product) {
// 			const productInCart = state.cart.find(item => item.id === product.id);
// 			if (productInCart) {
// 				productInCart.quantity++;
// 			} else {
// 				state.cart.push(product);
// 			}
// 		}
// 	},
// 	actions: {
// 		addToCart({
// 			commit
// 		}, product) {
// 			commit('addToCart', product);
// 		}
// 	}
// });

export default store